package com.bjpowernode.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class ConfigTestServlet extends GenericServlet {
    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        //获取ServletConfig对象
        ServletConfig config = this.getServletConfig();
        //输出该对象
        out.print("Servlet对象是："+ config.toString());
        out.print("<br>");

        //获取<Servlet-name>标签信息
        String servletName = config.getServletName();
        out.print("<servlet-name>"+servletName+"</servlet-name>");
        out.print("<br>");

        //通过ServletConfig对象的两个方法，可以获取web.xml文件的初始化配置信息
        Enumeration<String> initParameterNames = config.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){ //是否有更多的元素
            String parameterName = initParameterNames.nextElement(); //取元素
            String parameterVal = config.getInitParameter(parameterName); //通过名字取name
            out.print(parameterName+"=" + parameterVal);
            out.print("<br>");
        }
        //实际上获取了一个Servlet对象的初始化信息，可以不用获取ServletConfig对象，直接通过this也可以
        Enumeration<String> names = this.getInitParameterNames();
        while (names.hasMoreElements()){
            String name = names.nextElement();
            String value = this.getInitParameter(name);
            //打印到后台
            System.out.println(name+ "="+value);
        }
        //怎么获取ServletContext对象呢？
        //第一章方式：通过ServletConfig对象获取ServletContext对象。
        ServletContext application = config.getServletContext();
        out.print("<br>" + application);

        //第二种方式：通过this获取ServletContext对象
        ServletContext application2 = this.getServletContext();
        out.print("<br>" + application2);
    }
}
